
import { useState } from "react";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import { View } from "@tarojs/components";
import { useBoolean, useCreation } from "ahooks";

import ByCol from "@/components/ui/ByCol";
import ByRow from "@/components/ui/ByRow";
import Moment from "@/components/app/Moment";
import Money from "@/components/app/Money";
import Page from "@/components/common/Page";
import ByCell from "@/components/ui/ByCell";
import ByText from "@/components/ui/ByText";
import Card from "@/components/common/Card";
import ByIcon from "@/components/ui/ByIcon";
import ByButton from "@/components/ui/ByButton";
import PaneConfirmedByERP from "./components/PaneConfirmedByERP";
import PaneConfirmedDetail from "./components/PaneConfirmedDetail";
import PopupRecordTimeline from "./components/PopupRecordTimeline";
import PopupBalanceConfirm from "./components/PopupBalanceConfirm";

import useFetch from "@/hooks/useFetch";
import ApiBalance from "@/api/balance";
import ApiFinance from "@/api/finance";


type BalanceDetail = {
  address: string;
  customerName: string;

  gzBalanceApplyDate: number;
  workerPrincipal: string;
  balanceAmount: number;
  /**
   * 结算状态 0.待申请结算，1.待erp确认，2.待项目经理确认，3.待付款
   */
  balanceStatus: 0 | 1 | 2 | 3;
  details: {
    amount: number;
    dataId: number;
    balanceId: number;
    formula: string;
    isBalance: boolean;
    isCanEdit: boolean;
    itemName: string;
    remark: string;
    sortId: number;
    specialCode: string;
    templateDetailId: number;
  }[];
};

const enumBalanceStatus = {
  0: { label: "待申请结算", color: "info" },
  1: { label: "待erp确认", color: "warning" },
  2: { label: "已确认", color: "warning" },
  // 3: { label: "已确认", color: "primary" },
  // // 这个状态目前不好断定是否存在和具体意义
  // 4: { label: "已付款", color: "success" },
} as const;

export default () => {
  const { params } = useRouter();
  const intentCustomerId = Number(params.intentCustomerId);

  // 获取项目结算信息
  const { data, refresh } = useFetch<BalanceDetail>(
    ApiBalance.customerBalanceDetail,
    { defaultParams: [{ intentCustomerId }] }
  );

  //
  const [visible, { setFalse, setTrue }] = useBoolean();

  // 项目经理确认弹窗
  const [confirmed, confirmedHandler] = useBoolean(true);

  const balanceStatus = data?.balanceStatus;
  const balanceStatusConfig = enumBalanceStatus[balanceStatus || 0];

  useDidShow(() => {
    confirmedHandler.setFalse();
    data && refresh();
  });

  // 获取模板类型
  const { data: templateData } = useFetch<{ details: any[] }>(
    ApiFinance.getPaymentTemplate,
    { defaultParams: [{ intentCustomerId }] }
  );

  // 剩余未付尾款金额
  const remainAmount = useCreation(() => {
    const target = templateData?.details.find((e) => e.specialCode == "fk4");

    if (!target) return 0;

    return target.payableAmount - target.appliedAmount;
  }, [templateData]);


  // 是否展示申请结算按钮
  const [showApplyBtn, setShowApplyBtn] = useState(false)
  const { loading: loadingApply, run: runApply } = useFetch(ApiFinance.settlementSubmit, {
    manual: true,
    showLoading: true,
    onSuccess: () => refresh()
  })
  const handleApply = async () => {
    // 待结算申请且无不符合规范项
    const { confirm } = await Taro.showModal({
      title: "申请结算标准",
      content: "本项目符合结算标准，您可以提交结算申请",
      confirmText: "提交申请",
      confirmColor: "#1677ff",
    });

    if (confirm) {
      runApply({ intentCustomerId })
    }
  }

  return (
    <>
      <Page
        footerSticky
        slotFooter={
          <>
            {/* {balanceStatus === 2 && (
              <ByButton
                size="large"
                className="w-2/3"
                onClick={confirmedHandler.setTrue}
              >
                确认
              </ByButton>
            )} */}

            {
              showApplyBtn &&
              <ByButton
                size="large"
                className="w-2/3"
                loading={loadingApply}
                onClick={handleApply}
              >
                申请结算
              </ByButton>
            }

            {balanceStatus === 2 && remainAmount > 0 && (
              <ByButton
                size="large"
                className="w-2/3"
                to={`/packageProject/pages/engineeringFunds/apply?specialCode=fk4&intentCustomerId=${intentCustomerId}`}
              >
                申请付款
              </ByButton>
            )}
          </>
        }
      >
        <>
          <Card className="m-3">
            <View className="text-lg">{data?.customerName}</View>
            <View className="text-third mt-2 text-sm">{data?.address}</View>
          </Card>

          {data && (
            <Card
              className="m-3"
              title={
                <ByRow content="between" align="center">
                  <View>
                    {balanceStatusConfig && (
                      <ByText type={balanceStatusConfig.color}>
                        {balanceStatusConfig.label}
                      </ByText>
                    )}
                  </View>

                  <ByIcon name="Clock" size={30} onClick={setTrue} />
                </ByRow>
              }
            >
              <ByRow wrap>
                <ByCol span={6}>
                  <ByCell label="项目经理" vertical>
                    {data?.workerPrincipal}
                  </ByCell>
                </ByCol>
                <ByCol span={6}>
                  <ByCell label="申请时间" vertical>
                    <Moment value={data?.gzBalanceApplyDate} />
                  </ByCell>
                </ByCol>

                {balanceStatus !== undefined && balanceStatus > 0 && (
                  <>
                    <ByCol span={6}>
                      <ByCell label="尾款金额" vertical>
                        <Money type="primary" value={data?.balanceAmount} />
                      </ByCell>
                    </ByCol>

                    <ByCol span={6}>
                      <ByCell label="剩余未付尾款" vertical>
                        <Money value={remainAmount} />
                      </ByCell>
                    </ByCol>
                  </>
                )}
              </ByRow>
            </Card>
          )}

          {
            balanceStatus === 0 ?
              <PaneConfirmedByERP
                intentCustomerId={intentCustomerId}
                onShowApplyBtn={setShowApplyBtn}
              /> : <PaneConfirmedDetail
                details={data?.details || []} />
          }

        </>
      </Page>

      {visible && (
        <PopupRecordTimeline
          intentCustomerId={intentCustomerId}
          onCancel={setFalse}
        />
      )}

      {confirmed && (
        <PopupBalanceConfirm
          intentCustomerId={intentCustomerId}
          onCancel={confirmedHandler.setFalse}
        />
      )}
    </>
  );
};
